<template>
  <div class="app-container">
    景区表单
    <el-form label-width="120px" ref="sceneryInfo" :model="sceneryInfo" :rules="rules">
      <!-- <el-form label-width="120px">
        <el-form-item label="景区名">
          <el-input
            v-model="sceneryInfo.sName"
            placeholder=" 示例：写景区的名字"
          />
      </el-form-item>-->

      <!-- 具体地址 -->
      <el-form-item label="省份名称" prop="address">
        <el-input v-model="cityInfo.province" :rows="10"/>
      </el-form-item>
      <el-form-item label="市名称" prop="address">
        <el-input v-model="cityInfo.city" :rows="10"/>
      </el-form-item>
      <el-form-item label="区名称" prop="address">
        <el-input v-model="cityInfo.district" :rows="10"/>
      </el-form-item>
      <!-- 开放时间 -->
      <el-form-item label="市编号" prop="uPassword">
        <el-input v-model="cityInfo.cityCode"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { validatanum } from "@/utils/validate";
import { validataisnotnull } from "@/utils/validate";
import teacher from "@/api/teacher";
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";
import user from "@/api/user";
import scenery from "@/api/scenery";
import Tinymce from "@/components/Tinymce";
import city from "@/api/city";
export default {
  components: { ImageCropper, PanThumb, Tinymce },
  data() {
    const validateTeacherSort = (rule, value, callback) => {
      if (!validatanum(value)) {
        callback(new Error("请输入正确的数字"));
      } else {
        callback();
      }
    };
    const validateTeacherisnotnull = (rule, value, callback) => {
      if (!validataisnotnull(value)) {
        callback(new Error("不可以为空"));
      } else {
        callback();
      }
    };
    return {
      oneCityList: [], //课程类型，一级分类
      twoCityList: [], //课程分类，二级分类
      threeCityList: [], //课程分类，三级分类
      cityInfo: {},
      imgUrls: "",
      //表单数据
      saveBtnDisabled: false, //这个是判断这个按是不是不可以用，默认是true，不可以用
      BASE_API: process.env.BASE_API, // 接口API地址
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      rules: {
        name: [
          { required: true, message: "请输入讲师名称", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" }
        ],
        sort: [
          { required: true, trigger: "blur", validator: validateTeacherSort }
        ],
        level: [
          {
            required: true,
            trigger: "blur",
            validator: validateTeacherisnotnull
          }
        ],
        career: [
          { required: true, message: "请输入讲师资历", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ],
        intro: [
          { required: true, message: "请输入讲师简介", trigger: "blur" },
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur"
          }
        ]
      },
      dialogVisible: false,
      limitImg: 10, //限制图片上传的数量
      fileList: []
    };
  },
  // 多个操作公用一个组件，我们需要回归测试，我们就需要用watch来监听他们，发生了变化，要记得清空数据
  created() {
    console.log("created");
    if (this.$route.params && this.$route.params.cityName) {
      const cityArray = this.$route.params.cityName.split("|");
      console.log("$route.params.0=" + cityArray);
      if (cityArray.length >= 2) {
        console.log("$route.params.0=" + cityArray[0]);
        console.log("$route.params.1=" + cityArray[1]);
        // 分别拿出分割后的字符串
        this.cityInfo.province = cityArray[0]; // 第一个部分
        this.cityInfo.city = cityArray[1]; // 第二个部分
        console.log("$route.params.id=" + cityInfo.province);
        console.log("$route.params.id=" + cityInfo.city);
      }
    }
    this.init();
  },
  watch: {
    // 监听器，监听我们vue中所有属性
    $route(to, from) {
      console.log("created");
      //新增获取省份

      this.init();
    }
  },
  methods: {
    init() {
      //获取路由中的id
      console.log("$route.params.id=" + this.$route.params);
      console.log("$route.params.id=" + this.$route.params.cityName);
      if (this.$route.params && this.$route.params.name) {
        city.cityCityByName(this.$route.params.name).then(response => {
          //数据回显
          this.cityInfo = response.data;
          // this.fileList = response.data.imagesListHou;
          // this.imgUrls = response.data.imgUrls;
          // console.log(this.fileList);

          //回显城市数据
          // this.getCityInfo();
        });
      } else {
        console.log("清空数据");
        this.sceneryInfo = {};
        //获取所有省级
        this.getAllProvince();
      }
    },

    getCityInfo() {
      //回显省级
      this.getAllProvince();
      //回显市级
      this.getTwoByOneId(this.sceneryInfo.province);
      //回显区级
      this.getThreeByTwoId(this.sceneryInfo.city);
    },
    getAllProvince() {
      city.getAllProvince().then(response => {
        //数据回显
        this.oneCityList = response.data.provinceCity;

        console.log(response);
        console.log(this.oneCityList);
      });
    },
    //判断表单数据是否全部填满
    isEduTeacherForm() {
      if (
        (((this.sceneryInfo.name != null && this.sceneryInfo.sort) != null &&
          this.sceneryInfo.level) != null && this.sceneryInfo.career) != null
      )
        this.saveBtnDisabled = false;
    },
    saveOrUpdate() {
      this.cityInfo.name = this.cityInfo.district;
      if (this.cityInfo.id) {
        //id存在执行更新
        this.updateSceneryInfo();
      } else {
        this.saveScenery();
      }
    },
    saveScenery() {
      console.log(this.cityInfo);
      city.CityAdd(this.cityInfo).then(response => {
        //到这里一定成功了，因为失败了都被拦截了
        //1.提示成功W
        this.$message({
          type: "success",
          message: "添加成功!"
        });
        //2.跳转到查询讲师那里
        //路由跳转
        this.$router.push({ path: "/dict/cityProvinceList" });
      });
    },
    updateSceneryInfo() {
      city.cityUpdateCounter(this.cityInfo).then(response => {
        //到这里一定成功了，因为失败了都被拦截了
        //1.提示成功
        this.$message({
          type: "success",
          message: "修改成功!"
        });
        //2.跳转到查询讲师那里
        //路由跳转
        this.$router.push({ path: "/dict/cityProvinceList" });
      });
    },
    close() {
      //关闭操作
      this.imagecropperShow = false;

      //imagecropperKey这个东西要每次上传他都不一样才行
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    cropSuccess(data) {
      //成功后的回调函数
      //获取出url，显示在页面
      this.sceneryInfo.headImg = data;
      //关闭表格
      this.close();
    },
    submitUpload() {
      let { uploadFiles, action, data } = this.$refs.upload;
      const formData = new FormData();
      //需要带过去的参数，可以放在formData里面
      uploadFiles.map(file => {
        formData.append("files", file.raw);
      });
      scenery.fileUploads(2, formData).then(resp => {
        if (resp.code === 20000) {
          this.$notify({
            title: "成功",
            message: "上传成功",
            type: "success"
          });
          this.fileList = resp.data;
        }
      });
    },

    beforeAvatarUpload(file) {
      const imgType = file.type === "image/jpeg" || file.type === "image/png";
      const imgSize = file.size / 1024 / 1024 < 5;

      if (!imgType) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
      }
      if (!imgSize) {
        this.$message.error("图片大小不能超过 5MB!");
      }
      return imgType && imgSize;
    },
    handleSuccess(file) {
      //这里写上传成功后的处理逻辑，如果存在修改的话可以将图片的uid、name等存下，
      //待handleRemove有移除的话，就可以将对应不存在的图片移除
      // this.sceneryInfo.imgUrls=file;
      //获取一开始带过来的url
      console.log(file);
      // this.imgUrls = this.sceneryInfo.imgUrls;
      this.imgUrls = this.imgUrls + "," + file.data;
      console.log(this.imgUrls);
      this.sceneryInfo.imgUrls = this.imgUrls; //把值又赋回去，不然像前三行那个操作每次返回都是一样的了
      this.dialogVisible = false;
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传${this.limit}个文件`);
    },
    handleRemove(file, fileList) {
      console.log("被删除的url是" + file.url);
      console.log(file.url);
      let originalString = this.imgUrls;

      // 将字符串转换为数组，使用逗号和空格分割
      let stringArray = originalString.split(",");

      // 要删除的字符串
      let stringToDelete = file.url;

      // 查找要删除的字符串在数组中的索引
      let index = stringArray.indexOf(stringToDelete);

      // 如果找到了要删除的字符串，则从数组中删除
      if (index !== -1) {
        stringArray.splice(index, 1);
      }

      // 将数组转换回字符串，使用逗号和空格连接
      this.imgUrls = stringArray.join(",");

      console.log("删除后的imgUrls");
      console.log(this.imgUrls);
      this.sceneryInfo.imgUrls = this.imgUrls;
    },
    handlePreview(file) {
      console.log(file);
    },

    //省获取市级
    getTwoByOneId(province) {
      console.log(this.twoCityList);
      console.log(this.threeCityList);
      city.getAllPCity(province).then(response => {
        //数据回显
        this.twoCityList = response.data.cityCity;
      });
    },
    //市获取区
    getThreeByTwoId() {
      console.log(this.sceneryInfo.province);
      console.log(city);
      //数据回显
      city
        .getAllDistrictThree(this.sceneryInfo.province, this.sceneryInfo.city)
        .then(response => {
          //数据回显
          this.threeCityList = response.data.districtCity;
        });
    }
  }
};
</script>